package com.qf.controller;

import com.qf.captcha.CaptchaCodeManager;
import com.qf.pojo.DtsAdmin;
import com.qf.pojo.DtsPermission;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@CrossOrigin("*")
@RestController
@RequestMapping("/admin/auth")
@Slf4j
public class AdminAuthController {

    @Autowired
    DtsRoleService roleService;

    @Autowired
    DtsPermissionService permissionServicea;


    @RequestMapping("/logout")
    public Object logout(){

        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        log.debug("退出成功");
        return ResponseUtil.ok();

    }


    //登录后获取用户的基本信息
    @RequestMapping("/info")
    public Object info(){

        //当前用户对象
        Subject currentUser = SecurityUtils.getSubject();
        DtsAdmin admin = (DtsAdmin) currentUser.getPrincipal();
        String username = admin.getUsername();
        String avatar = admin.getAvatar();

        Map<String, Object> data = new HashMap<>();
        data.put("name", username);
        data.put("avatar", avatar);

        Integer[] roleIds = admin.getRoleIds();

        Set<String> roles = roleService.findRoleByIds(roleIds);
        Set<String> perms = permissionServicea.findPermsByRoleIds(roleIds);

        data.put("roles", roles);
        data.put("perms", perms);

        return ResponseUtil.ok(data);
    }



    @RequestMapping("/login")
    public Object login(@RequestBody Map<String, String> map){

        String code = map.get("code");
        String username = map.get("username");
        String password = map.get("password");
        String uuid = map.get("uuid");

        //判断
        if(StringUtils.isEmpty(uuid) || StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(code)){
            return ResponseUtil.badArgument();
        }

        //校验验证码
        String captcha = CaptchaCodeManager.getCachedCaptcha(uuid);

        if(captcha == null){
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_EXPIRED);
        }

        if(!code.equalsIgnoreCase(captcha)){
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_ERROR);
        }

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        //登录
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);

            System.out.println(subject.isAuthenticated());
            System.out.println(subject.hasRole("超级管理员") ? "是超级管理员" : "不是超级管理员");
            System.out.println(subject.isPermitted("admin:category:read") ? "有权限" : "没有权限");

            return ResponseUtil.ok(subject.getSession().getId());
        }catch (UnknownAccountException e){
            e.printStackTrace();
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT_OR_PASSWORD);
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT_OR_PASSWORD);
        }catch (LockedAccountException e){
            e.printStackTrace();
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_LOCK_ACCOUNT);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_AUTH);
        }

    }

    @RequestMapping("/captchaImage")
    public Object captchaImage() throws IOException {

        //生成一个5位的验证码
        String code = VerifyCodeUtils.generateVerifyCode(1);
        //生成一个uuid
        String uuid = UUID.randomUUID().toString();
        //添加验证码到缓存，  方便后期 登录校验验证码
        boolean isSuccess = CaptchaCodeManager.addToCache(uuid, code, 10);
        //判断是否成功
        if (!isSuccess) {
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_FREQUENCY);
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //生成 图片
        VerifyCodeUtils.outputImage(111, 36, outputStream, code);
        //拼接 下行参数的格式
        Map<String, Object> data = new HashMap<>();
        data.put("uuid",uuid);
        data.put("img",Base64.encode(outputStream.toByteArray()));

        return ResponseUtil.ok(data);
    }

}
